<template>
  <div class="work-order-container">
    <el-page-header content="运维工单管理" style="margin-bottom: 20px;"></el-page-header>

    <!-- 筛选和操作区（新增处理人ID筛选） -->
    <el-card shadow="hover" class="filter-card">
      <div class="filter-container">
        <el-select
            v-model="statusFilter"
            placeholder="筛选工单状态"
            clearable
            style="width: 200px; margin-right: 20px;"
            @change="fetchWorkOrderList"
        >
          <el-option label="待办" value="1"></el-option>
          <el-option label="处理中" value="2"></el-option>
          <el-option label="已处理" value="3"></el-option>
          <el-option label="处理失败" value="4"></el-option>
        </el-select>

        <!-- 新增：处理人ID筛选输入框 -->
        <el-input
            v-model="processorIdFilter"
            placeholder="请输入处理人ID筛选"
            clearable
            style="width: 200px; margin-right: 20px;"
            @clear="fetchWorkOrderList"
            @keyup.enter.native="fetchWorkOrderList"
        ></el-input>

        <el-button type="primary" @click="openCreateDialog">
          <i class="el-icon-plus"></i> 创建工单
        </el-button>
      </div>
    </el-card>

    <!-- 工单列表（内容不变） -->
    <el-card shadow="hover" class="stat-card" style="margin-top: 20px;">
      <el-table
          :data="workOrderList"
          border
          style="width: 100%;"
          v-loading="tableLoading"
      >
        <el-table-column prop="repairId" label="工单ID" width="140"></el-table-column>
        <el-table-column prop="faultId" label="关联故障ID" width="120"></el-table-column>
        <el-table-column prop="deviceId" label="设备ID" width="120"></el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template slot-scope="scope">
            <el-tag :type="getStatusTag(scope.row.repairResult).type">
              {{ getStatusTag(scope.row.repairResult).text }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="120">
          <template slot-scope="scope">
            <el-tag :type="getPriorityTag(scope.row.priority).type">
              {{ getPriorityTag(scope.row.priority).text }}
            </el-tag>
          </template>
        </el-table-column>
        <!-- 维修照片列 -->
        <el-table-column label="维修照片" width="140">
          <template slot-scope="scope">
            <el-image
                :src="scope.row.repairImages"
                style="width: 80px; height: 80px; border-radius: 4px;"
                fit="cover"
                preview-src-list="[scope.row.repairImages]"
                v-if="scope.row.repairImages"
                class="photo-preview"
            ></el-image>
            <div v-else class="no-photo">无照片</div>
          </template>
        </el-table-column>
        <el-table-column prop="processorId" label="处理人" width="120"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="openDetailDialog(scope.row.repairId)">
              查看详情
            </el-button>
            <el-button
                type="text"
                size="mini"
                @click="handleProcessWorkOrder(scope.row)"
                :disabled="!canProcess(scope.row.repairResult)"
                v-if="scope.row.repairResult === 1 || scope.row.repairResult === 4"
            >
              {{ getProcessBtnText(scope.row.repairResult) }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页（内容不变） -->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          style="margin-top: 15px; text-align: right;"
      ></el-pagination>
    </el-card>

    <!-- 详情弹窗（内容不变） -->
    <el-dialog
        title="工单详情"
        :visible.sync="detailDialogVisible"
        width="700px"
    >
      <div v-if="currentWorkOrder" class="detail-content">
        <el-descriptions column="1" border>
          <el-descriptions-item label="工单ID">{{ currentWorkOrder.repairId }}</el-descriptions-item>
          <el-descriptions-item label="关联故障ID">{{ currentWorkOrder.faultId }}</el-descriptions-item>
          <el-descriptions-item label="设备ID">{{ currentWorkOrder.deviceId }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTag(currentWorkOrder.repairResult).type">
              {{ getStatusTag(currentWorkOrder.repairResult).text }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="优先级">
            <el-tag :type="getPriorityTag(currentWorkOrder.priority).type">
              {{ getPriorityTag(currentWorkOrder.priority).text }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="处理人">{{ currentWorkOrder.processorId || '未分配' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentWorkOrder.createTime }}</el-descriptions-item>
          <el-descriptions-item label="开始处理时间">{{ currentWorkOrder.startTime || '未开始' }}</el-descriptions-item>
          <el-descriptions-item label="处理结束时间">{{ currentWorkOrder.endTime || '未结束' }}</el-descriptions-item>
          <el-descriptions-item label="维修备注">{{ currentWorkOrder.repairNotes || '无' }}</el-descriptions-item>
          <el-descriptions-item label="维修图片" v-if="currentWorkOrder.repairImages">
            <el-image
                :src="currentWorkOrder.repairImages"
                style="width: 300px; height: 200px;"
                fit="contain"
            ></el-image>
          </el-descriptions-item>
        </el-descriptions>
        <el-button
            type="text"
            @click="openStatusHistoryDialog(currentWorkOrder.repairId)"
            style="margin-top: 10px;"
        >
          查看状态变更历史
        </el-button>
      </div>
    </el-dialog>

    <!-- 状态历史弹窗（内容不变） -->
    <el-dialog
        title="状态变更历史"
        :visible.sync="statusHistoryDialogVisible"
        width="600px"
    >
      <el-table
          :data="statusHistoryList"
          border
          style="width: 100%;"
          height="400"
      >
        <el-table-column prop="operateTime" label="操作时间" width="180"></el-table-column>
        <el-table-column prop="operatorId" label="操作人" width="120"></el-table-column>
        <el-table-column prop="oldStatusDesc" label="变更前状态"></el-table-column>
        <el-table-column prop="newStatusDesc" label="变更后状态"></el-table-column>
        <el-table-column prop="remark" label="备注"></el-table-column>
      </el-table>
    </el-dialog>

    <!-- 创建工单弹窗（内容不变） -->
    <el-dialog
        title="创建运维工单"
        :visible.sync="createDialogVisible"
        width="500px"
    >
      <el-form
          :model="createForm"
          :rules="createRules"
          ref="createFormRef"
          label-width="120px"
      >
        <el-form-item label="关联故障ID" prop="faultId">
          <el-input v-model="createForm.faultId" placeholder="请输入关联的故障ID"></el-input>
        </el-form-item>
        <el-form-item label="设备ID" prop="deviceId">
          <el-input v-model="createForm.deviceId" placeholder="请输入设备ID"></el-input>
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="createForm.priority" placeholder="请选择优先级">
            <el-option label="紧急" value="1"></el-option>
            <el-option label="普通" value="2"></el-option>
            <el-option label="低" value="3"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCreateForm">确认创建</el-button>
      </div>
    </el-dialog>

    <!-- 处理工单弹窗（内容不变） -->
    <el-dialog
        :title="processDialogTitle"
        :visible.sync="processDialogVisible"
        width="500px"
    >
      <el-form
          :model="processForm"
          :rules="processRules"
          ref="processFormRef"
          label-width="120px"
      >
        <el-form-item label="处理人ID" prop="processorId" v-if="showProcessorInput">
          <el-input v-model="processForm.processorId" placeholder="请输入处理人ID"></el-input>
        </el-form-item>
        <el-form-item label="维修备注" prop="repairNotes" v-if="showRepairNotes">
          <el-input
              v-model="processForm.repairNotes"
              type="textarea"
              rows="4"
              placeholder="请输入维修详情"
          ></el-input>
        </el-form-item>
        <el-form-item label="失败原因" prop="failureReason" v-if="showFailureReason">
          <el-input
              v-model="processForm.failureReason"
              type="textarea"
              rows="4"
              placeholder="请输入失败原因"
          ></el-input>
        </el-form-item>
        <el-form-item label="维修图片" prop="repairImages" v-if="showRepairImages">
          <el-upload
              action=""
              :auto-upload="false"
              :on-change="handleImageChange"
              list-type="picture"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="processDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitProcessForm">确认提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { Message } from "element-ui";
import { workorder } from "@/api/workorder";

export default {
  name: "WorkOrderManage",
  data() {
    return {
      // 列表数据（新增处理人ID筛选字段）
      workOrderList: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      tableLoading: false,
      statusFilter: "",
      processorIdFilter: "", // 新增：处理人ID筛选值

      // 弹窗控制（内容不变）
      detailDialogVisible: false,
      createDialogVisible: false,
      processDialogVisible: false,
      statusHistoryDialogVisible: false,

      // 当前操作的工单数据（内容不变）
      currentWorkOrder: null,
      currentProcessType: "",
      statusHistoryList: [],

      // 创建工单表单（内容不变）
      createForm: {
        faultId: "",
        deviceId: "",
        priority: 2
      },
      createRules: {
        faultId: [{ required: true, message: "请输入关联故障ID", trigger: "blur" }],
        deviceId: [{ required: true, message: "请输入设备ID", trigger: "blur" }],
        priority: [{ required: true, message: "请选择优先级", trigger: "change" }]
      },

      // 处理工单表单（内容不变）
      processForm: {
        processorId: "",
        repairNotes: "",
        failureReason: "",
        repairImages: ""
      },
      processRules: {
        processorId: [{ required: true, message: "请输入处理人ID", trigger: "blur" }],
        repairNotes: [{ required: true, message: "请输入维修备注", trigger: "blur" }],
        failureReason: [{ required: true, message: "请输入失败原因", trigger: "blur" }]
      }
    };
  },
  computed: {
    // 处理弹窗动态显示字段（内容不变）
    processDialogTitle() {
      const titles = {
        assign: "分配处理人",
        start: "开始处理工单",
        complete: "完成工单处理",
        fail: "标记处理失败"
      };
      return titles[this.currentProcessType] || "处理工单";
    },
    showProcessorInput() {
      return this.currentProcessType === "assign";
    },
    showRepairNotes() {
      return this.currentProcessType === "complete";
    },
    showFailureReason() {
      return this.currentProcessType === "fail";
    },
    showRepairImages() {
      return this.currentProcessType === "complete";
    }
  },
  mounted() {
    this.fetchWorkOrderList();
  },
  methods: {
    // 获取工单列表（仅新增processorIdFilter参数传递）
    fetchWorkOrderList() {
      this.tableLoading = true;
      const statusNum = this.statusFilter ? Number(this.statusFilter) : undefined;
      console.log('发送的筛选参数:', {
        status: statusNum || undefined,
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        processorId: this.processorIdFilter, // 优先使用筛选框值，否则用当前用户ID
      });
      workorder.list({
        status: statusNum || undefined,
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        processorId: this.processorIdFilter, // 传递筛选值
      })
          .then(res => {
            this.workOrderList = res.data.records.reverse();
            this.total = res.data.total;
          })
          .catch(err => {
            Message.error("获取工单列表失败：" + (err.message || err));
          })
          .finally(() => {
            this.tableLoading = false;
          });
    },

    // 分页处理（内容不变）
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.fetchWorkOrderList();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchWorkOrderList();
    },

    // 状态标签样式（内容不变）
    getStatusTag(status) {
      const statusMap = {
        1: {text: "待办", type: "warning"},
        2: {text: "处理中", type: "info"},
        3: {text: "已处理", type: "success"},
        4: {text: "处理失败", type: "danger"}
      };
      return statusMap[status] || {text: "未知", type: "default"};
    },

    // 优先级标签样式（内容不变）
    getPriorityTag(priority) {
      const priorityMap = {
        1: {text: "紧急", type: "danger"},
        2: {text: "普通", type: "primary"},
        3: {text: "低", type: "info"}
      };
      return priorityMap[priority] || {text: "未知", type: "default"};
    },

    // 处理按钮文本（内容不变）
    getProcessBtnText(status) {
      const btnTextMap = {
        1: "分配处理人",
        2: "完成处理",
        3: "重新处理",
        4: "重新分配处理人"
      };
      return btnTextMap[status] || "操作";
    },

    // 判断是否可处理（内容不变）
    canProcess(status) {
      return [1, 2, 4].includes(status);
    },

    // 打开详情弹窗（内容不变）
    openDetailDialog(repairId) {
      workorder.detail({workOrderId: repairId})
          .then(res => {
            this.currentWorkOrder = res.data;
            this.detailDialogVisible = true;
          })
          .catch(err => {
            Message.error("获取工单详情失败：" + (err.message || err));
          });
    },

    // 打开状态历史弹窗（内容不变）
    openStatusHistoryDialog(repairId) {
      workorder.history({workOrderId: repairId})
          .then(res => {
            this.statusHistoryList = res.data;
            this.statusHistoryDialogVisible = true;
          })
          .catch(err => {
            Message.error("获取状态历史失败：" + (err.message || err));
          });
    },

    // 打开创建工单弹窗（内容不变）
    openCreateDialog() {
      this.createForm = {
        faultId: "",
        deviceId: "",
        priority: null
      };
      if (this.$refs.createFormRef) {
        this.$refs.createFormRef.resetFields();
      }
      this.createDialogVisible = true;
    },

    // 提交创建工单表单（内容不变）
    submitCreateForm() {
      this.$refs.createFormRef.validate(valid => {
        if (!valid) return;

        workorder.create(this.createForm)
            .then(() => {
              Message.success("工单创建成功");
              this.createDialogVisible = false;
              this.fetchWorkOrderList();
            })
            .catch(err => {
              Message.error("创建工单失败：" + (err.message || err));
            });
      });
    },

    // 处理工单入口（内容不变）
    handleProcessWorkOrder(row) {
      this.currentWorkOrder = {...row};
      if (row.repairResult === 1) {
        this.currentProcessType = "assign";
      }else if(row.repairResult === 4){
        this.currentProcessType = "assign";
      }
      else if (row.repairResult === 2) {
        this.$confirm("请选择处理方式", "提示", {
          confirmButtonText: "完成处理",
          cancelButtonText: "标记失败",
          type: "info"
        })
            .then(() => {
              this.currentProcessType = "complete";
              this.processDialogVisible = true;
            })
            .catch(() => {
              this.currentProcessType = "fail";
              this.processDialogVisible = true;
            });
        return;
      }
      this.processDialogVisible = true;
      this.processForm = {
        processorId: "",
        repairNotes: "",
        failureReason: "",
        repairImages: ""
      };
    },

    // 提交处理表单（内容不变）
    submitProcessForm() {
      this.$refs.processFormRef.validate(valid => {
        if (!valid) return;

        const repairId = this.currentWorkOrder.repairId;
        let apiMethod, params;

        switch (this.currentProcessType) {
          case "assign":
            apiMethod = workorder.assign;
            params = {workOrderId: repairId, processorId: this.processForm.processorId};
            break;
          case "start":
            apiMethod = workorder.start;
            params = {workOrderId: repairId};
            break;
          case "complete":
            apiMethod = workorder.complete;
            params = {
              workOrderId: repairId,
              notes: this.processForm.repairNotes,
              images: this.processForm.repairImages
            };
            break;
          case "fail":
            apiMethod = workorder.fail;
            params = {
              workOrderId: repairId,
              failureReason: this.processForm.failureReason
            };
            break;
          default:
            return;
        }

        apiMethod(params)
            .then(() => {
              Message.success("工单处理成功");
              this.processDialogVisible = false;
              this.fetchWorkOrderList();
            })
            .catch(err => {
              Message.error("处理工单失败：" + (err.message || err));
            });
      });
    },

    // 图片上传处理（内容不变）
    handleImageChange(file) {
      this.processForm.repairImages = URL.createObjectURL(file.raw);
    }
  }
};
</script>
<style scoped>
.work-order-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.filter-card {
  padding: 15px;
  margin-bottom: 20px;
}

.filter-container {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.detail-content {
  margin-top: 10px;
}
</style>